import {call, Module, register, SagaGenerator} from "../core-native";
import TabPage from "../pages/TabPage";
import {RootState} from "../types";
import AsyncStorage from "@react-native-async-storage/async-storage";
import {emits, storages} from "../constants";
import {restaurantsInitList} from "../constants/restaurantsInitList";
// @ts-ignore
import RCTNativeAppEventEmitter from "react-native/Libraries/EventEmitter/RCTNativeAppEventEmitter";
import _ from "lodash";
import {restaurantListIdx} from "../types/TabState";

class TabModule extends Module<RootState, "tab"> {
    *onEnter(): SagaGenerator {
        const userInfoStr = yield* call(() => AsyncStorage.getItem(storages.KEY_USERINFO));
        if (userInfoStr) {
            this.setState({userInfo: JSON.parse(userInfoStr)});
        }
        const token: RootState["app"]["tab"]["token"] = yield* call(() => AsyncStorage.getItem(storages.KEY_TOKEN));
        this.setState({token});
    }
    /**
     * 注销登录
     */
    *handleLogout() {
        yield* call(() => AsyncStorage.removeItem(storages.KEY_USERINFO));
        yield* call(() => AsyncStorage.removeItem(storages.KEY_TOKEN));
        this.setState({userInfo: null, token: null});
        RCTNativeAppEventEmitter.emit(emits.EMIT_LOGOUT);
    }
    /**
     * restaurantList排序
     * @param listIdx 排序index
     */
    *sortRestaurants(listIdx: restaurantListIdx) {
        let newList = _.cloneDeep(restaurantsInitList);

        switch (listIdx) {
            case restaurantListIdx.BestSaller:
                newList = newList.sort((prev, next) => next.hot - prev.hot).filter(item => item.isBussiness);
                break;
            case restaurantListIdx.Nearby:
                newList = newList.sort((prev, next) => prev.nearby - next.nearby).filter(item => item.isBussiness);
                break;
            case restaurantListIdx.ComingSoon:
                newList = newList.filter(item => !item.isBussiness);
                break;
        }
        this.setState({restaurantsList: newList});
    }
}

const initState: RootState["app"]["tab"] = {
    token: null,
    userInfo: null,
    restaurantsList: restaurantsInitList,
};

const module = register(new TabModule("tab", initState));
export const TabActions = module.getActions();
export const Tab = module.attachLifecycle(TabPage);
